package com.ruoyi.project.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.*;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.system.domain.SysCompany;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.constant.UserConstants;
//import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysPostService;
import com.ruoyi.project.system.service.ISysRoleService;
import com.ruoyi.project.system.service.ISysUserService;

/**
 * 用户信息
 *
 * @author leslie1015
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class SelfcomUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 注册
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody SysUser user, @RequestBody SysCompany sysCompany) {

        // 手机号也就是账号
//    user.setPhonenumber(user.getUserName());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，该登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }

        //user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        //user.setComId(SecurityUtils.getCurrComId());
        user.setStatus(UserStatus.APPROVAL.getCode()); //待审核
        user.setAdminFlag(0);
        return toAjax(userService.registerUser(user, sysCompany));
    }

    /**
     * 添加管理员
     */
    @PostMapping("/add-admin")
    public AjaxResult addAdmin(@RequestBody SysUser user) {

        // 手机号也就是账号
//    user.setPhonenumber(user.getUserName());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，该登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        if(StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        //user.setComId(SecurityUtils.getCurrComId());
        user.setStatus(UserStatus.OK.getCode()); //待审核
        user.setAdminFlag(1);
        user.setSuperAdminFlag(1);
        return toAjax(userService.addAdmin(user));
    }

    /**
     * 获取普通用户列表
     */
    @ApiOperation("用户列表")
    @PreAuthorize("@ss.hasPermi('selfcom:user:list')")
    @GetMapping("/user-list")
    public TableDataInfo userList(String userName, String department) {
        SysUser user = new SysUser();
        user.setUserName(userName);
        user.setDepartment(department);
        startPage();
        user.setRole("user");
        List<SysUser> list = userService.userList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('selfcom:user:list')")
    @GetMapping("/user-export")
    public AjaxResult userExport(SysUser user) {
        user.setRole("user");
        List<SysUser> list = userService.userList(user);
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        return util.exportExcel(list, "用户数据");
        return null;
    }

    /**
     * 获取管理员用户列表
     */
    @PreAuthorize("@ss.hasPermi('selfcom:user:list')")
    @GetMapping("/admin-list")
    public TableDataInfo adminList(SysUser user) {
//    user.setComId(SecurityUtils.getCurrComId());
        startPage();
        user.setRole("administrator");
//    user.setSuperAdminFlag(1);
        List<SysUser> list = userService.userList(user);
        return getDataTable(list);
    }

    /**
     * 审批用户
     */
    @PreAuthorize("@ss.hasPermi('selfcom:user:edit')")
    @Log(title = "用户审批", businessType = BusinessType.UPDATE)
    @PutMapping("/change-status/{userIds}")
    public AjaxResult userStat(@PathVariable Long[] userIds, String status, String reason) {

        return toAjax(userService.updateStatus(userIds, status, reason));
    }

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('selfcom:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        user.setComId(SecurityUtils.getCurrComId());
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('selfcom:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        return util.exportExcel(list, "用户数据");
        return null;
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('selfcom:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        List<SysUser> userList = util.importExcel(file.getInputStream());
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        String operName = loginUser.getUsername();
//        String message = userService.importUser(userList, updateSupport, operName);
//        return AjaxResult.success(message);
        return null;
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        return util.importTemplateExcel("用户数据");
        return null;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('selfcom:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId) {
        Long userIdc = StringUtils.isBlank(userId) ? SecurityUtils.getCurrUserId() : Long.valueOf(userId);
        AjaxResult ajax = AjaxResult.success();
//    List<SysRole> roles = roleService.selectRoleAll();

//    ajax.put("roles", SysUser.isAdmin(userIdc) ? roles
//        : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
////    ajax.put("posts", postService.selectPostAllByCom(SecurityUtils.getCurrComId()));
//    if (StringUtils.isNotNull(userIdc)) {
//      ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userIdc));
////      ajax.put("postIds", postService.selectPostListByUserId(userIdc));
//      ajax.put("roleIds", roleService.selectRoleListByUserId(userIdc));
//    }
        ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userIdc));

        return ajax;
    }

    /**
     * 新增用户
     */
    @ApiOperation("添加用户")
    @PreAuthorize("@ss.hasPermi('selfcom:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，该登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        // 存明文密码，方便管理员查看
        user.setPlaintext(user.getPassword());
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setComId(SecurityUtils.getCurrComId());
//        user.setAdminFlag(0);
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
//    @PreAuthorize("@ss.hasPermi('selfcom:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        // 手机号也就是账号
//        user.setPhonenumber(user.getUserName());
        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        // 修改用户支持修改密码
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @PreAuthorize("@ss.hasPermi('selfcom:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PreAuthorize("@ss.hasPermi('selfcom:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('selfcom:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 验证用户
     */
    @GetMapping("/check-user/{userName}")
    public AjaxResult checkUser(@PathVariable String userName){

        SysUser user = userService.selectUserByUserName(userName);
        if (user == null || !UserStatus.OK.getCode().equals(user.getStatus())) {
            throw new CustomException("用户不存在！");
        }

        if (StringUtils.isBlank(user.getPhonenumber())) {
            throw new CustomException("用户未绑定手机号！");
        }
        Map result = new HashMap();
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        result.put("phone", user.getPhonenumber().replaceAll("(\\d{3})\\d{0,5}(\\w{0,3})", "$1****$2"));
        result.put("uid", uuid);
        result.put("userName", user.getUserName());
        return AjaxResult.success(result);
    }

    /**
     * 修改密码
     */
    @ApiOperation("修改密码")
    @PostMapping("/change-pwd")
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    public AjaxResult changepwd(String oldPassword, String newPassword){
//        SysUser user = userService.selectUserByUserName(sysUser.getUserName());
//        if (user == null || !UserStatus.OK.getCode().equals(user.getStatus())) {
//            throw new CustomException("用户不存在！");
//        }
//        String verifyKey = Constants.SMS_CODE_KEY+sysUser.getUserName();
//        String uid = redisCache.getCacheObject(verifyKey);
//        if (uid==null || !uid.equals(sysUser.getUid())) {
//            throw new CustomException("用户验证失败，无法修改密码！");
//        }
//        redisCache.deleteObject(verifyKey);
//
//        SysUser updateUser = new SysUser();
//        updateUser.setUserId(user.getUserId());
//        updateUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
//
//        return AjaxResult.success(userService.updateUser(updateUser));
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }
}